package at.guigu.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //1 将ServletRequest强转为HttpServletRequest对象
        HttpServletRequest req = (HttpServletRequest) request;

        //2 在数组中存储登陆之前可访问的所有资源并对其放行
        //2.1 将登陆之前就可访问到的资源存到数组中
        String[] urls = {"/imgs/", "/css/", "/login.jsp", "/loginServlet", "/register.jsp", "/registerServlet" ,"/checkCodeServlet"};
        //2.2 获取当前访问的资源路径
        String url = req.getRequestURL().toString();
        //2.3 循环判断是否为需要放行的资源，若是则放行并退出该方法，不会再继续执行循环后面的代码
        for (String u : urls) {
            if (url.contains(u)) {
                chain.doFilter(request, response);
                return;
            }
        }
        //3 获取Session对象并获取其中的User对象
        //3.1 获取Session对象
        HttpSession session = req.getSession();
        //3.2 获取Session中的User对象
        Object user = session.getAttribute("user");
        if (user != null) {//若用户已登录则放行
            //放行前需要对request对象的数据进行处理

            //放行
            chain.doFilter(request, response);
            //放行后需要对response数据进行处理

        } else {//若用户未登录
            req.setAttribute("login_msg", "您尚未登录，请先进行登录！");
            //注意：forward的第一个参数用req或request都一样
            req.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }
}